/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.insa.flopenshop;

import java.util.Iterator;

/**
 *
 * @author strokyl
 */
public class GetTachePlacableDepuisIterable implements GetTachePlacableOrdonne {

	private class IteratorFiltrant implements Iterable<SousTache>, Iterator<SousTache> {
		private Iterable<SousTache> iterableOriginal;
		private Iterator<SousTache> iterator;
		private final int date;
		private final Solution solution;

		public void setIterableOriginal(Iterable<SousTache> iterableOriginal) {
			this.iterableOriginal = iterableOriginal;
		}
		private SousTache next;

		private IteratorFiltrant(Iterable<SousTache> iterableOriginal, int date, Solution solution) {
			this.iterableOriginal = iterableOriginal;
			this.date = date;
			this.solution = solution;
		}

		private void moveToNext() {
			SousTache possibleNext;
			next = null;
			while(next == null && iterator.hasNext()) {
				possibleNext = iterator.next();
				if(possibleNext != null && solution.estPlacable(date, possibleNext)) {
					next = possibleNext;
				}
			}
		}

		@Override
		public Iterator<SousTache> iterator() {
			iterator = iterableOriginal.iterator();
			moveToNext();
			return this;
		}

		@Override
		public boolean hasNext() {
			return next != null;
		}

		@Override
		public SousTache next() {
			SousTache cpNext = next;
			moveToNext();
			return cpNext;
		}

		@Override
		public void remove() {
			throw new UnsupportedOperationException("Not supported yet.");
		}

	}

	private Iterable<SousTache> iterableOriginal;

	public GetTachePlacableDepuisIterable(Iterable<SousTache> iterableOriginal) {
		this.iterableOriginal = iterableOriginal;
	}

	public void setIterableOriginal(Iterable<SousTache> iterableOriginal) {
		this.iterableOriginal = iterableOriginal;
	}


	@Override
	public Iterable<SousTache> getTachePlacable(int date, Solution solution) {
		return new IteratorFiltrant(iterableOriginal, date, solution);
	}
		
}
